package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.MemberPhoneExsitException;
import com.atguigu.gulimall.member.exception.MemberUsernameExsitException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.utils.HttpUtils;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity default_status = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(default_status.getId());
        checkUserPhone(registVo.getPhone());
        checkUserUsername(registVo.getUsername());
        memberEntity.setUsername(registVo.getUsername());
        memberEntity.setMobile(registVo.getPhone());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);
        baseMapper.insert(memberEntity);


    }

    @Override
    public void checkUserUsername(String username) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count>0){
            throw new MemberUsernameExsitException();
        }
    }

    @Override
    public void checkUserPhone(String phone) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count>0){
            throw new MemberPhoneExsitException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String username = loginVo.getUsername();

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", username).or().eq("mobile", username));
        if (memberEntity!=null){
            //判断密码
            String DBApassword = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(loginVo.getPassword(), DBApassword);
            if (matches){
                return memberEntity;
            }else {
                return null;
            }
        }else {
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialUser user) throws Exception {
        String access_token = user.getAccess_token();

//            https://gitee.com/api/v5/user
            HashMap<String, String> query = new HashMap<>();
            query.put("access_token", access_token);
            //获取gitee用户信息
            HttpResponse giteeUserInfo = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
            if(giteeUserInfo.getStatusLine().getStatusCode()==200){
                String json = EntityUtils.toString(giteeUserInfo.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                //根据id查询是否存在
                MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", id));
                if (memberEntity!=null){
                    //存在 更新token
                    memberEntity.setAccessToken(access_token);
                    baseMapper.updateById(memberEntity);
                    return memberEntity;
                }else {
                    //注册 创建新用户
                    MemberEntity newMember = new MemberEntity();
                    newMember.setSocialId(Long.parseLong(id));
                    newMember.setAccessToken(access_token);
                    newMember.setNickname(name);
                    baseMapper.insert(newMember);
                    return newMember;
                }
            }else {
                return null;
            }
    }

}